package com.jiehoo.elove.robot;



import java.io.IOException;
import java.text.MessageFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import rath.msnm.SwitchboardSession;
import rath.msnm.entity.MsnFriend;
import rath.msnm.msg.MimeMessage;

public class PendingMessage {
  private static Log log = LogFactory.getLog(PendingMessage.class);

  private static final MessageFormat firstFormat = new MessageFormat(
      "{0} �ղŷ�������Ϣ��\r\n��{1,number}��");

  private static final MessageFormat otherFormat = new MessageFormat(
      "\r\n��{0,number}��");

  private static final int MAX_LENGTH = 400;

  SwitchboardSession session;

  MsnFriend poster;

  MimeMessage message;

  StringBuffer messageBuffer = new StringBuffer();

  int pendingCount=1;

  public PendingMessage(SwitchboardSession session, MsnFriend poster, MimeMessage message) {
    this.session = session;
    this.poster = poster;
    this.message = message;
    Object[] parameters = { poster.getLoginName(), new Integer(pendingCount++) };
    wrapMessage(parameters, firstFormat, message);
  }

  private void wrapMessage(Object[] parameters, MessageFormat format,
      MimeMessage message) {
    messageBuffer.append(format.format(parameters));
    messageBuffer.append(message.getMessage());
  }

  public void addMessage(MimeMessage message) {
    Object[] parameters = { new Integer(pendingCount++) };
    wrapMessage(parameters, otherFormat, message);
  }

  public void addMessage(SwitchboardSession session,MimeMessage message) {
    if (session!=null&&session.equals(this.session)) {
      this.session=session;
    }
    addMessage(message);
  }

  public void send() {
    try {
      int count = messageCount();
      int start = 0;
      int end = 0;
      for (int i = 0; i < count; i++) {
        end = start + MAX_LENGTH;
        if (end > messageBuffer.length()) {
          end = messageBuffer.length();
        }
        message.setMessage(messageBuffer.substring(start, end));
        session.sendMessage(message);
        start = end;
      }
    }
    catch (IOException e) {
      log.error("Send pending message error!", e);
    }
  }

  private int messageCount() {
    int count = 0;
    count = messageBuffer.length() / MAX_LENGTH;
    if (messageBuffer.length() > MAX_LENGTH * count) {
      count++;
    }
    return count;
  }

}